package com.ruoyi.project.download;

import com.ruoyi.common.utils.file.QiniuUtils;
import com.ruoyi.common.utils.file.ZipFileUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.zerocarbon.domain.Declaration;
import com.ruoyi.project.zerocarbon.domain.DeclareFile;
import com.ruoyi.project.zerocarbon.mapper.DeclarationMapper;
import com.ruoyi.project.zerocarbon.mapper.DeclareFileMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Controller for download file.<p>This class also support <tt>Range</tt> header request for partial download.
 *
 * @author zw
 * @title 下载文件接口
 */
@Slf4j
@Api("下载接口")
@RestController
public class DownloadController {

    @Resource
    private QiniuUtils qiniuUtils;

    private final DownloadRequestProcessor processor;
    private final DeclarationMapper declarationMapper;
    private final DeclareFileMapper declareFileMapper;

    public DownloadController(DownloadRequestProcessor processor,DeclarationMapper declarationMapper,DeclareFileMapper declareFileMapper) {
        this.processor = processor;
        this.declarationMapper = declarationMapper;
        this.declareFileMapper = declareFileMapper;
    }

    /**
     * 下载文件
     *
     * @param path 下载文件的真实路径
     * @title 下载系统文件
     */
    @ApiOperation("下载文件预览视频等")
    @ResponseBody
    @GetMapping("/common/download2")
    public void doDownload(@RequestParam String path, HttpServletRequest request, HttpServletResponse response) throws IOException {

        processor.process(path, request, response);
    }

    @ApiOperation("下载申报zip,单个")
    @ResponseBody
    @GetMapping("/common/download2/decoration")
    public AjaxResult doDownloadDecoration(@RequestParam Long declarationId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Declaration declaration = declarationMapper.selectDeclarationById(declarationId);
        String path = "/home/declaration/file/"+declaration.getHead().trim()+"-"+declarationId+".zip";
        if (!new File(path).exists()){
            List<DeclareFile> declareFiles = declareFileMapper.selectByDeclarationId(declarationId);
            if (!CollectionUtils.isEmpty(declareFiles)){
                ZipFileUtils.toZip(declareFiles.stream().map(DeclareFile::getPath).collect(Collectors.toList()),new FileOutputStream(new File(path)));
            }else {
                log.info("该用户无文件");
                return AjaxResult.success();
            }
        }
        processor.process(path, request, response);
        return AjaxResult.success();
    }

    @ApiOperation("下载申报zip,单个")
    @ResponseBody
    @GetMapping("/common/download3/decoration")
    public void doDownloadDecorationResponse(@RequestParam Long declarationId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Declaration declaration = declarationMapper.selectDeclarationById(declarationId);
        String path = "/home/declaration/file/"+declaration.getHead().trim()+"-"+declarationId+".zip";
        if (!new File(path).exists()){
            List<DeclareFile> declareFiles = declareFileMapper.selectByDeclarationId(declarationId);
            if (!CollectionUtils.isEmpty(declareFiles)){
                ZipFileUtils.toZip(declareFiles.stream().map(DeclareFile::getPath).collect(Collectors.toList()),new FileOutputStream(new File(path)));
            }else {
                log.info("该用户无文件");
                return;
            }
        }
        processor.process(path, request, response);
    }

    private ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 100,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>());

    @ApiOperation("下载申报zip,list")
    @ResponseBody
    @RequestMapping("/common/download2/decoration/list")
    public void doDownloadDecorationList(Long[] declarationIdList, HttpServletRequest request, HttpServletResponse response) throws IOException {
        for (int i = 0; i < declarationIdList.length; i++) {
            Long id = declarationIdList[i];
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    Long declarationId = id;
                    try {
                        Declaration declaration = declarationMapper.selectDeclarationById(declarationId);
                        String path = "/home/declaration/file/"+declaration.getHead().trim()+"-"+declarationId+".zip";
                        if (!new File(path).exists()){
                            List<DeclareFile> declareFiles = declareFileMapper.selectByDeclarationId(declarationId);
                            if (!CollectionUtils.isEmpty(declareFiles)){
                                ZipFileUtils.toZip(declareFiles.stream().map(DeclareFile::getPath).collect(Collectors.toList()),new FileOutputStream(new File(path)));
                            }else {
                                log.info("该用户无文件");
                                return;
                            }
                        }
                        processor.process(path, request, response);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });

        }
    }

}
